const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');


let myPath = path.join(__dirname,'/data.json');
http.createServer((req,res) => {
    // post请求数据在请求体里
    let str = '';
    req.on('data',chunk => {
        str += chunk;
    })
    req.on('end', () => {
        // console.log(str)
        let obj = JSON.parse(str);
        let name = obj.username;
        let pwd = obj.password;
        fs.readFile(myPath,(e,data) => {
            if (e) {
                console.log(e)
            }
            else{
                let list = JSON.parse(data);
                for (let i = 0; i < list.length; i++) {
                    // console.log(list[0])
                    if (list[i].username == name && list[i].password == pwd) {
                        res.writeHead(200,{"Content-Type":"text/plain;charset=utf8"})
                        res.write('登录成功！')
                        res.end()
                        return;
                    }
                }
                res.writeHead(200,{"Content-Type":"text/plain;charset=utf8"})
                res.write('用户名、密码不正确。')
                res.end()
            }
        })
    })
}).listen(8081);
console.log('server is listening 8081')